import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Smartphone, MessageSquare, ArrowLeft } from "lucide-react";
import { useUser } from "@/contexts/UserContext";
import { showSuccess } from "@/hooks/use-toast";

import { getCodeImg, sendSmsCode } from "@/api/common";

const Login = () => {
  const [phone, setPhone] = useState("");
  const [captchaInput, setCaptchaInput] = useState("");
  const [code, setCode] = useState("");
  const [codeUuid, setCodeUuid] = useState("");
  const [loading, setLoading] = useState({
    login: false,
    captchaImg: false,
  });
  const [countdown, setCountdown] = useState(0);
  const [codeSent, setCodeSent] = useState(false);

  const [imgpath, setImgpath] = useState("");
  const [imgUuid, setImgUuid] = useState("");

  const { login } = useUser();

  // 验证状态
  const [errors, setErrors] = useState({
    phone: "",
    captcha: "",
    code: "",
  });
  const navigate = useNavigate();

  // 校验函数
  const phoneRegex = /^1[3-9]\d{9}$/;
  const isValidPhone = (phone: string) => phoneRegex.test(phone);
  const isValidCaptcha = (input: string) => input.length > 0;
  const isValidCode = (code: string) => code.length === 6;

  // 生成新的验证码
  const generateCaptcha = () => {
    getCodeImg().then((json: any) => {
      const { captchaEnabled, img, uuid } = json;
      if (captchaEnabled) {
        setImgpath(`data:image/gif;base64,${img}`);
        setImgUuid(uuid);
      }
    });
  };

  // 验证输入
  const validateInputs = () => {
    const newErrors = { phone: "", captcha: "", code: "" };

    if (!phone) {
      newErrors.phone = "请输入手机号码";
    } else if (!isValidPhone(phone)) {
      newErrors.phone = "请输入正确的手机号码";
    }

    if (codeSent && !code) {
      newErrors.code = "请输入手机验证码";
    } else if (codeSent && !isValidCode(code)) {
      newErrors.code = "请输入6位验证码";
    }

    setErrors(newErrors);
    return Object.values(newErrors).every((error) => !error);
  };

  // 发送验证码
  const handleSendCode = async () => {
    // 验证手机号和图片验证码
    if (!isValidPhone(phone)) {
      setErrors((prev) => ({ ...prev, phone: "请输入正确的手机号码" }));
      return;
    }

    if (!isValidCaptcha(captchaInput)) {
      setErrors((prev) => ({ ...prev, captcha: "图片验证码错误" }));
      return;
    }

    setErrors({ phone: "", captcha: "", code: "" });
    setLoading((prev) => ({ ...prev, captchaImg: true }));

    const codePost = await sendSmsCode({
      uuid: imgUuid,
      code: captchaInput,
      phone: phone,
    });
    setLoading((prev) => ({ ...prev, captchaImg: false }));
    if (codePost.code == 200) {
      setCodeUuid(codePost.data);

      setCodeSent(true);
      setCountdown(60);
      showSuccess(`验证码已发送至 ${phone}，请注意查收`, "验证码已发送");
    } else if (codePost.code == 500) {
      generateCaptcha();
    }

    // 倒计时
    const timer = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  // 验证登录
  const handleLogin = async () => {
    if (!validateInputs() || !codeSent) {
      return;
    }
    setLoading((prev) => ({ ...prev, login: true }));
    const isLogin = await login(phone, codeUuid, code);
    setLoading((prev) => ({ ...prev, login: false }));
    navigate("/");
    // 模拟验证过程
    // setTimeout(() => {
    //   setLoading(false);
    //   // 检查是否是新用户
    //   const isNewUser = !localStorage.getItem(`user_${phone}`);

    //   login(phone);
    //   toast({
    //     title: isNewUser ? "注册成功" : "登录成功",
    //     description: isNewUser ? "欢迎加入视频分析平台！" : "欢迎回来！",
    //   });

    //   // 新用户跳转到个人信息完善页面
    //   if (isNewUser) {
    //     navigate("/profile?first=true");
    //   } else {
    //     navigate("/");
    //   }
    // }, 1500);
  };

  // 输入变化处理
  const handlePhoneChange = (value: string) => {
    setPhone(value);
    if (errors.phone) {
      setErrors((prev) => ({ ...prev, phone: "" }));
    }
  };

  const handleCaptchaChange = (value: string) => {
    setCaptchaInput(value);
    if (errors.captcha) {
      setErrors((prev) => ({ ...prev, captcha: "" }));
    }
  };

  const handleCodeChange = (value: string) => {
    setCode(value);
    if (errors.code) {
      setErrors((prev) => ({ ...prev, code: "" }));
    }
  };

  // 获取焦点
  const handleFocus = (key: string) => {
    setErrors((prev) => ({ ...prev, [key]: "" }));
  };

  // 失去焦点
  const handleBlur = (key: string) => {
    let errorMsg = "";
    if (key == "phone") {
      if (!isValidPhone(phone)) {
        errorMsg = "请输入正确的手机号码";
      }
    } else if (key == "captcha") {
      if (!isValidCaptcha(captchaInput)) {
        errorMsg = "请输入图片验证码";
      }
    } else if (key == "code") {
      if (!isValidCode(code)) {
        errorMsg = "请输入6位验证码";
      }
    }
    setErrors((prev) => ({ ...prev, [key]: errorMsg }));
  };

  useEffect(() => {
    generateCaptcha();
  }, []);

  return (
    <div className="min-h-screen bg-[var(--gradient-secondary)] flex items-center justify-center p-4">
      <div className="w-full max-w-md space-y-6">
        {/* 返回按钮 */}
        <Button
          variant="ghost"
          onClick={() => navigate("/")}
          className="flex items-center gap-2 text-muted-foreground hover:text-foreground transition-[var(--transition-smooth)]"
        >
          <ArrowLeft className="h-4 w-4" />
          返回首页
        </Button>

        <Card className="shadow-[var(--shadow-elegant)] border-0 bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/60">
          <CardHeader className="text-center space-y-4">
            <div className="mx-auto w-16 h-16 bg-[var(--gradient-primary)] rounded-full flex items-center justify-center shadow-[var(--shadow-button)]">
              <Smartphone className="h-8 w-8 text-primary-foreground" />
            </div>
            <div>
              <CardTitle className="text-2xl bg-[var(--gradient-primary)] bg-clip-text text-transparent">
                手机登录
              </CardTitle>
              <CardDescription className="mt-2">
                输入手机号码和验证码，新用户将自动注册
              </CardDescription>
            </div>
          </CardHeader>

          <CardContent className="space-y-6">
            {/* 手机号输入 */}
            <div className="space-y-2">
              <Label htmlFor="phone">手机号码</Label>
              <Input
                id="phone"
                type="tel"
                placeholder="请输入11位手机号码"
                value={phone}
                onFocus={() => handleFocus("phone")}
                onBlur={() => handleBlur("phone")}
                onChange={(e) =>
                  handlePhoneChange(
                    e.target.value.replace(/\D/g, "").slice(0, 11)
                  )
                }
                className={`text-center text-lg ${
                  errors.phone ? "border-destructive" : ""
                }`}
              />
              {errors.phone && (
                <p className="text-sm text-destructive mt-1">{errors.phone}</p>
              )}
            </div>

            {/* 图片验证码和发送验证码 */}
            <div className="space-y-2">
              <Label>图片验证码</Label>
              <div className="flex gap-2 items-center">
                <div className="relative">
                  <img
                    src={imgpath}
                    alt="验证码"
                    className={`h-10 w-[120px] border rounded cursor-pointer ${
                      !imgpath ? "opacity-0" : ""
                    }`}
                    onClick={generateCaptcha}
                  />
                </div>
                <Input
                  type="text"
                  placeholder="请输入验证码"
                  value={captchaInput}
                  onFocus={() => handleFocus("captcha")}
                  onBlur={() => handleBlur("captcha")}
                  onChange={(e) =>
                    handleCaptchaChange(
                      e.target.value.replace(/\D/g, "").slice(0, 2)
                    )
                  }
                  className={`flex-1 ${
                    errors.captcha ? "border-destructive" : ""
                  }`}
                />
                <Button
                  onClick={handleSendCode}
                  disabled={
                    loading.captchaImg ||
                    countdown > 0 ||
                    !isValidPhone(phone) ||
                    !isValidCaptcha(captchaInput)
                  }
                  className="hover:shadow-[var(--shadow-button)] transition-[var(--transition-smooth)] whitespace-nowrap"
                  size="default"
                >
                  {loading.captchaImg ? (
                    <>
                      <MessageSquare className="h-4 w-4 mr-2 animate-pulse" />
                      发送中...
                    </>
                  ) : countdown > 0 ? (
                    `${countdown}s后重新发送`
                  ) : codeSent ? (
                    <>
                      <MessageSquare className="h-4 w-4 mr-2" />
                      重新发送
                    </>
                  ) : (
                    <>
                      <MessageSquare className="h-4 w-4 mr-2" />
                      发送验证码
                    </>
                  )}
                </Button>
              </div>
              {errors.captcha && (
                <p className="text-sm text-destructive mt-1">
                  {errors.captcha}
                </p>
              )}
            </div>

            {/* 手机验证码输入 */}
            <div className="space-y-2">
              <Label htmlFor="code">手机验证码</Label>
              <Input
                id="code"
                type="text"
                placeholder="请输入6位验证码"
                value={code}
                onChange={(e) =>
                  handleCodeChange(
                    e.target.value.replace(/\D/g, "").slice(0, 6)
                  )
                }
                className={`text-center text-xl ${
                  errors.code ? "border-destructive" : ""
                }`}
                disabled={!codeSent}
                onFocus={() => handleFocus("code")}
                onBlur={() => handleBlur("code")}
              />
              {errors.code && (
                <p className="text-sm text-destructive mt-1">{errors.code}</p>
              )}
            </div>

            {/* 登录/注册按钮 */}
            <Button
              onClick={handleLogin}
              disabled={loading.login || !codeSent || !isValidCode(code)}
              className="w-full hover:shadow-[var(--shadow-button)] transition-[var(--transition-smooth)]"
              size="lg"
            >
              {loading.login ? "验证中..." : "登录/注册"}
            </Button>
          </CardContent>
        </Card>

        <p className="text-xs text-center text-muted-foreground">
          登录即表示您同意我们的
          <Button variant="link" className="h-auto p-0 text-xs text-primary">
            服务条款
          </Button>
          和
          <Button variant="link" className="h-auto p-0 text-xs text-primary">
            隐私政策
          </Button>
        </p>
      </div>
    </div>
  );
};

export default Login;
